package util

import (
	"bufio"
	"bytes"
	"errors"
	"io"
	"os/exec"
	"strings"
)

/**
执行shell
    等待程序终止, 且监听实时响应
*/
type QueryLine func(line string)

func ExecShellMonitor(cmdString string, queryLine QueryLine) error {
	cmd := exec.Command("/bin/bash", "-c", cmdString)
	stdoutRs, err := cmd.StdoutPipe()
	if err != nil {
		return err
	}

	var stderr bytes.Buffer
	cmd.Stderr = &stderr

	readerRs := bufio.NewReader(stdoutRs)
	if err := cmd.Start(); err != nil {
		return err
	}
	for {
		line, errLine := readerRs.ReadString('\n')
		if errLine != nil || io.EOF == errLine {
			break
		}
		queryLine(line)
	}
	if err := cmd.Wait(); err != nil {
		return errors.New(stderr.String())
	}
	return nil
}

/*
	阻塞式的执行外部shell命令的函数,等待执行完毕并返回标准输出
	error　exit status 状态
	string　返回的数据stdout+stderr

	demo:
	out,err := ExecShell(cmd)
	if err != nil {
		fmt.Println("--- stderr ---")
		log.Printf("stderr: %v\n", out)
	}else{	"tool-nginx/common/common"

		fmt.Println("--- stdout ---")
		log.Printf("out: %v\n", out)
	}
*/
func ExecShell(s string) (string, error) {
	var stdout bytes.Buffer
	var stderr bytes.Buffer
	cmd := exec.Command("/bin/bash", "-c", s)
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr
	err := cmd.Run()
	return stdout.String() + stderr.String(), err
}

/**
判断软件是否存在
*/
func SoftwareExist(softwareName string) bool {
	str, _ := ExecShell("whereis " + softwareName)
	if strings.Count(str, softwareName) > 1 {
		return true
	}
	return false
}
